package controllers.manage.order;

import com.google.gson.Gson;
import controllers.BaseController;
import controllers.auth.Secure;
import controllers.auth.SkipAuth;
import enums.GoodsType;
import enums.OrderStatus;
import enums.PaymentType;
import helper.CSVUtils;
import helper.GenerateQrCodeUtil;
import helper.GlobalConfig;
import jodd.util.StringUtil;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import order.Order;
import order.OrderItem;
import play.Logger;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;
import util.common.ConvertUtil;
import util.common.DateUtil;

import java.io.File;
import java.text.DecimalFormat;
import java.util.*;


/**
 * 订单管理
 * Created by buhaoba on 2017/4/12.
 */
@With(BaseController.class)
public class OrderCtrl extends Controller {

    /**
     * 跳转到订单管理页面
     */
    public static void index(Integer pageNumber, String orderNumber, String startTime, String endTime, OrderStatus status, PaymentType payType, GoodsType orderType , Boolean frozenGoodsType){

        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtil.isNotBlank(orderNumber)) {
            searchMap.put("orderNumber", orderNumber);
        }

        if(StringUtil.isNotBlank(startTime)) {
            searchMap.put("startTime", startTime+" 00:00:00");
        }

        if(StringUtil.isNotBlank(endTime)) {
            searchMap.put("endTime", endTime+" 23:59:59");
        }

        if(status != null) {
            searchMap.put("status", status);
        }

        if(payType != null) {
            searchMap.put("payType", payType);
        }

        if(orderType != null && (frozenGoodsType == null || !frozenGoodsType)) {
            searchMap.put("orderType", orderType);
        }

        if(frozenGoodsType != null && frozenGoodsType) {
            searchMap.put("orderType0", GoodsType.PRODUCT );
            searchMap.put("orderType1", GoodsType.THIRDPARTY );
            searchMap.put("orderType2", GoodsType.NO_PRODUCT);

            flash.put("menuId" , "131");
        } else {
            flash.put("menuId", "17");
        }

        JPAExtPaginator<Order> resultPage = Order.findByCondition(searchMap, "id desc", pageNumber, GlobalConfig.PAGE_SIZE);
        Logger.info("getPageCount : %s" , resultPage.size());

       /* for(Order o : resultPage.getCurrentPage()) {
            Logger.info("orderNumber:%s" , o.orderNumber);
        }*/

        render(resultPage, pageNumber, orderNumber, startTime, endTime, status, payType, orderType , frozenGoodsType);
    }

    /**
     * 跳转到订单明细页面
     */
    public static void detail(long id, Integer pageNumber){
        Order order = Order.findById(id);
        List<Map<String,Object>> orderItems = null;
        if(order != null)
            orderItems = OrderItem.getListByOrderId(order);
        render(order, pageNumber, orderItems);
    }

    /**
     * 确认订单
     */
    public static void confirmOrder(long id){
        Map<String , Object> resultMap = new HashMap<>();
        Order order = Order.findById(id);
        if(order.status == OrderStatus.UNPAID){
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单尚未支付!");
            renderJSON(resultMap);
            return;
        }

        order.confirmStatus="ok";
        order.save();

        resultMap.put("success" , true);
        resultMap.put("msg" , "订单确认成功!");
        renderJSON(resultMap);
    }

    /**
     * 跳转到支付页面
     */
    @SkipAuth
    public static void pay(String orderNumber, String goodsType, String payType){
        Order order = Order.findByOrderNumber(orderNumber);
        render(orderNumber, goodsType, order, payType);
    }







    @SkipAuth
    private static String getOrCode(String codeUrl){
        System.out.println("------获取二维码");
        String filePath = "/public/upload/";// 存储二维码路径
        return GenerateQrCodeUtil.generateQrcode(codeUrl, filePath);
    }






    /**
     * 删除订单
     */
    public static void delete(long id , Integer pageNumber){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        Order order = Order.findById(id);

        // 删除订单子项
        List<OrderItem> orderItems = OrderItem.getListByOrder(order);
        for(OrderItem item : orderItems){
            item.deleted = DeletedStatus.DELETED;
            item.save();
        }

        // 删除订单
        order.deleted = DeletedStatus.DELETED;
        order.save();

        flash.put("msg" , "订单删除成功");
        redirect("/BS0017/admin/order/index/"+pageNumber);
    }



    //导出
    public static void exportExcel(String orderNumber,
                                   String startTime,
                                   String endTime,
                                   OrderStatus status
                                 ){

        Merchant merchant = Secure.getLoginUser().merchant;

        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtil.isNotBlank(orderNumber)) {
            searchMap.put("orderNumber", orderNumber);
        }

        if(StringUtil.isNotBlank(startTime)) {
            searchMap.put("startTime", startTime+" 00:00:00");
        }

        if(StringUtil.isNotBlank(endTime)) {
            searchMap.put("endTime", endTime+" 00:00:00");
        }

        if(status != null) {
            searchMap.put("status", status);
        }

        if(merchant != null){
            searchMap.put("merchantId", merchant.id);
        }



        JPAExtPaginator<Order> resultPage = Order.findByCondition(searchMap, "id desc", null, null);
//        Logger.info("getPageCount : %s" , resultPage.getCurrentPage());

        //标题
        LinkedHashMap<String,String> headerMap = new LinkedHashMap<>();
        headerMap.put("orderNumber","订单编号");
        headerMap.put("nickName","下单人");
        headerMap.put("createdAt","下单时间");
        headerMap.put("amount","金额");
        headerMap.put("orderStatusStr","支付状态");

        //数据列表
        List<Map> dataList = new ArrayList<>();
        DecimalFormat b = new DecimalFormat("#.00");
        if(resultPage != null){
            for(Order order : resultPage){
                Logger.info("orderNumber:%s" , order.orderNumber);
                Map<String,Object> row = new LinkedHashMap<>();
                row.put("orderNumber",order.orderNumber.toString());
                row.put("nickName",order.webUser != null ? order.webUser.nickName : " ");
                row.put("createdAt",DateUtil.dateToString(order.createdAt , "yyyy-MM-dd HH:mm:ss"));
                row.put("amount",b.format(order.amount));
                row.put("orderStatusStr",OrderStatus.getOrderStatus(order.status));

                dataList.add(row);

            }
        }

        File file = CSVUtils.createCSVFile(dataList , headerMap , "订单列表");
        renderBinary(file);

    }

    //打印订单
    public static void printOrders(String orderIds){
        Logger.info("-------------printOrders 打印订单,订单Id:%s:",orderIds);
        List<Order> orderList = Order.getPrintDataList(ConvertUtil.escapeSql(orderIds));
        Logger.info("-------------printOrders 打印订单orderList :%s:",new Gson().toJson(orderList));
        render(orderList);
    }

}
